package cn.wildfire.chat.app.main;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.wildfire.chat.app.extendsion.classes.LoginRequest;
import cn.wildfire.chat.app.extendsion.classes.Region;
import cn.wildfire.chat.app.extendsion.classes.ResponseEntity;
import cn.wildfire.chat.app.extendsion.classes.SecurityAnswerEntity;
import cn.wildfire.chat.app.extendsion.classes.SecurityQuestionEntity;
import cn.wildfire.chat.app.extendsion.https.OkHttpRequest;
import cn.wildfire.chat.app.extendsion.https.ReqCallBack;
import cn.wildfire.chat.app.extendsion.https.ServerUrlClient;
import cn.wildfire.chat.app.extendsion.ui.ToastTip;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;
import cn.wildfire.chat.kit.WfcBaseActivity;
import cn.wildfirechat.model.UserInfo;
import cn.wildfirechat.remote.ChatManager;

/**
 * @Author Administrator
 * @Date 2019/9/20
 * 注册设置密保
 */
public class SetSecurityQuestionActivity extends WfcBaseActivity {

    @BindView(R2.id.security_question_one)
    TextView securityQuestionOne;
    @BindView(R2.id.security_question_two)
    TextView securityQuestionTwo;
    @BindView(R2.id.security_question_three)
    TextView securityQuestionThree;
    @BindView(R2.id.et_security_question_one)
    EditText etSecurityQuestionOne;
    @BindView(R2.id.et_security_question_two)
    EditText etSecurityQuestionTwo;
    @BindView(R2.id.et_security_question_three)
    EditText etSecurityQuestionThree;
    @BindView(R2.id.btn_set_security_question_finish)
    Button btnSetSecurityQuestionFinish;

    private SecurityQuestionEntity securityQuestionEntity;
    private HashMap<String, Object> params = new HashMap<>();
    private Region region;
    private String addPasswordProtected;
    MyHandler myHandler = new MyHandler(this);

    /**
     * 账号与安全中心
     */
    UserInfo userInfo;
    boolean havaSecurityQuestions;

    private static class MyHandler extends Handler {
        private WeakReference<SetSecurityQuestionActivity> activityWeakReference;
        private SecurityQuestionEntity securityQuestionEntity;

        public MyHandler(SetSecurityQuestionActivity activity) {
            activityWeakReference = new WeakReference<SetSecurityQuestionActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            SetSecurityQuestionActivity activity = activityWeakReference.get();
            if (activity != null) {
                switch (msg.what) {
                    case 1:
                        securityQuestionEntity = (SecurityQuestionEntity) msg.obj;
                        activity.btnSetSecurityQuestionFinish.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                String questionOne = activity.etSecurityQuestionOne.getText().toString().trim();
                                String questionTwo = activity.etSecurityQuestionTwo.getText().toString().trim();
                                String questionThree = activity.etSecurityQuestionThree.getText().toString().trim();

                                if (TextUtils.isTextEmpty(questionOne) || TextUtils.isTextEmpty(questionTwo) || TextUtils.isTextEmpty(questionThree)) {
                                    ToastTip.tip(activity.getString(R.string.security_question_have_to_fill_in_all));
                                    return;
                                }

                                SecurityAnswerEntity securityAnswerEntityOne = new SecurityAnswerEntity(securityQuestionEntity.getResult().get(0).getId(), questionOne);
                                SecurityAnswerEntity securityAnswerEntityTwo = new SecurityAnswerEntity(securityQuestionEntity.getResult().get(1).getId(), questionTwo);
                                SecurityAnswerEntity securityAnswerEntityThree = new SecurityAnswerEntity(securityQuestionEntity.getResult().get(2).getId(), questionThree);
                                List<SecurityAnswerEntity> securityAnswerEntities = new ArrayList<>();
                                securityAnswerEntities.add(securityAnswerEntityOne);
                                securityAnswerEntities.add(securityAnswerEntityTwo);
                                securityAnswerEntities.add(securityAnswerEntityThree);

                                // 账号与安全中心
                                if (activity.userInfo != null) {

                                    String userId = activity.userInfo.uid;
                                    securityAnswerEntityOne.setUid(userId);
                                    securityAnswerEntityTwo.setUid(userId);
                                    securityAnswerEntityThree.setUid(userId);
                                    activity.params.put("encryptedRelationReqs", securityAnswerEntities);

                                    OkHttpRequest.getInstance(activity).requestAsynJsonObject(ServerUrlClient.ADD_SET_PASSWORD_PROTECTED, activity.params, new ReqCallBack<Object>() {
                                        @Override
                                        public void onReqSuccess(Object result) {
                                            if (!TextUtils.isTextEmpty(result.toString())) {
                                                try {
                                                    ResponseEntity responseEntity = new ResponseEntity(result.toString());
                                                    if (responseEntity.isSuccess()) {
                                                        activity.securitySetResult(1);
                                                    } else {
                                                        ToastTip.tip(responseEntity.message);
                                                        activity.securitySetResult(0);
                                                    }
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        }

                                        @Override
                                        public void onReqFailed(String errorMsg) {
                                            activity.securitySetResult(0);
                                        }
                                    }).request();
                                }
                                // 其他
                                else {
                                    if (activity.addPasswordProtected != null || !TextUtils.isTextEmpty(activity.addPasswordProtected)) {
                                        securityAnswerEntityOne.setUid(ChatManager.Instance().getUserId());
                                        securityAnswerEntityTwo.setUid(ChatManager.Instance().getUserId());
                                        securityAnswerEntityThree.setUid(ChatManager.Instance().getUserId());
                                        activity.params.put("encryptedRelationReqs", securityAnswerEntities);
                                    } else {
                                        activity.params.put("encryptedList", securityAnswerEntities);
                                    }

                                    if (activity.addPasswordProtected != null || !TextUtils.isTextEmpty(activity.addPasswordProtected)) {
                                        OkHttpRequest.getInstance(activity).requestAsynJsonObject(ServerUrlClient.ADD_SET_PASSWORD_PROTECTED, activity.params, new ReqCallBack<Object>() {
                                            @Override
                                            public void onReqSuccess(Object result) {
                                                if (!TextUtils.isTextEmpty(result.toString())) {
                                                    try {
                                                        ResponseEntity<String, String> responseEntity = new ResponseEntity<>(result.toString());
                                                        if (responseEntity.isSuccess()) {
                                                            // 进入主界面
                                                            Intent intent = new Intent(activity, MainActivity.class);
                                                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                                            activity.startActivity(intent);
                                                            ToastTip.tip(activity.getString(R.string.setting_success));
                                                            activity.finish();
                                                        } else {
                                                            ToastTip.tip(responseEntity.message);
                                                        }
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                            }

                                            @Override
                                            public void onReqFailed(String errorMsg) {

                                            }
                                        }).request();
                                    } else {
                                        OkHttpRequest.getInstance(activity).requestAsynJsonObject(ServerUrlClient.REGISTER, activity.params, new ReqCallBack<Object>() {
                                            @Override
                                            public void onReqSuccess(Object result) {
                                                if (!TextUtils.isTextEmpty(result.toString())) {
                                                    try {
                                                        ResponseEntity<String, String> responseEntity = new ResponseEntity<>(result.toString());
                                                        if (responseEntity.isSuccess()) {
                                                            ToastTip.tip(activity.getString(R.string.register_success));
                                                            /**
                                                             * TODO 注册完成后，自动填充登入页面
                                                             */
                                                            new LoginRequest(activity, String.valueOf(activity.params.get("mobile")), String.valueOf(activity.params.get("password")), activity.region, false);
                                                        } else {
                                                            ToastTip.tip(responseEntity.message);
                                                        }
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                            }

                                            @Override
                                            public void onReqFailed(String errorMsg) {
                                                Toast.makeText(activity, "注册失败!", Toast.LENGTH_SHORT).show();
                                            }
                                        }).request();
                                    }
                                }
                            }
                        });
                        break;
                    default:
                        break;
                }
            }
        }
    }

    private void registerToLogin() {
    }

    @Override
    protected void afterViews() {
        super.afterViews();
        Intent intent = getIntent();
        userInfo = intent.getParcelableExtra("_userInfo");
        if (userInfo != null) {
            havaSecurityQuestions = intent.getBooleanExtra("havaSecurityQuestions", false);
            refreshUI();
        } else {
            addPasswordProtected = intent.getStringExtra("AddPasswordProtected");
            if (addPasswordProtected != null || !TextUtils.isTextEmpty(addPasswordProtected)) {
            } else {
                HashMap<String, String> registerMessage = (HashMap<String, String>) intent.getSerializableExtra("registerMessage");
                region = intent.getParcelableExtra("region");
                params.putAll(registerMessage);
            }
        }
        getSecurityQuestion();
    }

    @Override
    protected int contentLayout() {
        return R.layout.activity_security_question;
    }

    private void refreshUI() {
        if (userInfo != null) {
            btnSetSecurityQuestionFinish.setVisibility(havaSecurityQuestions ? View.GONE : View.VISIBLE);
            if (havaSecurityQuestions) {
                setEditTextInputStyle(etSecurityQuestionOne, true);
                setEditTextInputStyle(etSecurityQuestionTwo, true);
                setEditTextInputStyle(etSecurityQuestionThree, true);
            } else {
                setEditTextInputStyle(etSecurityQuestionOne, false);
                setEditTextInputStyle(etSecurityQuestionTwo, false);
                setEditTextInputStyle(etSecurityQuestionThree, false);
            }
        }
    }

    /**
     * 设置输入框的内容显示或隐藏
     *
     * @param editText
     * @param hide
     */
    private void setEditTextInputStyle(EditText editText, boolean hide) {
        if (editText == null)
            return;
        if (hide) {
            editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            editText.setText("123456");
            editText.setClickable(false);
            editText.setEnabled(false);
        } else {
            editText.setInputType(InputType.TYPE_CLASS_TEXT);
            editText.setClickable(true);
            editText.setEnabled(true);
        }
    }

    /**
     * 回调设置密保问题结果
     *
     * @param ret 0失败，1成功
     */
    private void securitySetResult(int ret) {
        setResult((ret == 1) ? Activity.RESULT_OK : Activity.RESULT_CANCELED);
        finish();
    }

    @Override
    protected void setTitleCenterThenSetSearchView() {
        super.setTitleCenterThenSetSearchView();
        setToolbarOrReplaceType(true, 2);
        if (userInfo != null) {
            setReplaceTitle(null, R.string.security_question);
        } else {
            setReplaceTitle(null, R.string.set_security_question);
        }
        setSearchLayoutVisibility(false);
    }

    private void getSecurityQuestion() {
        OkHttpRequest.getInstance(this).requestAsynJsonObject(ServerUrlClient.GET_SECURITY_QUESTION, null, new ReqCallBack<Object>() {
            @Override
            public void onReqSuccess(Object result) {
                if (!TextUtils.isTextEmpty(result.toString())) {
                    try {
                        Gson gson = new Gson();
                        securityQuestionEntity = gson.fromJson(result.toString(), SecurityQuestionEntity.class);
                        securityQuestionOne.setText(securityQuestionEntity.getResult().get(0).getProblem());
                        securityQuestionTwo.setText(securityQuestionEntity.getResult().get(1).getProblem());
                        securityQuestionThree.setText(securityQuestionEntity.getResult().get(2).getProblem());

                        Message message = myHandler.obtainMessage();
                        message.what = 1;
                        message.obj = securityQuestionEntity;
                        myHandler.sendMessage(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {

            }
        }).request();
    }
}
